<?php

namespace shop\controllers;

use shop\service\UserService;
use teach\util\helper\ResponseHelper;
use Yii;
use yii\filters\VerbFilter;
use yii\web\Controller;

class UserController extends Controller
{
    public $enableCsrfValidation = false;

    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    '*' => ['post'],
                ],
            ],
        ];
    }

    /**
     * 用户在多小程序中提现
     * @return \yii\web\Response
     */
    public function actionCash()
    {
        $request = Yii::$app->request;
        $uid =  $request->post('uid');//用户在绣学问里面的uid
        $amount = $request->post('amount');//提现的金额
        $appid = $request->post('appid');//用户跳转目标的appid

        $msg = '';
        $flag = false;

        if (!$uid) {
            $msg = 'uid 不能为空';
        } elseif ( !$amount) {
            $msg = 'amount 不能为空';
        } elseif (!$appid) {
            $msg = 'appid 不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
           $where = " collect.appid = '{$appid}' AND mall.id = {$uid} ";
           $userService = new UserService();
           $user = $userService->userOne($where);
           if ($user) {
               //判断用户是否有这么多金额
               if (floatval($user['mall_total_fee']) < floatval($amount) || floatval($amount) < 1) {
                   $jsonData = ResponseHelper::buildJsonData(401, '对不起，您的金额有误');
                   return $this->asJson($jsonData);
               }
               //用户存在则入库
               $map = [
                   'openid' => $user['openid'],
                   'uid' => $uid,
                   'amount' => $amount,
                   'status' => 1,
                   'create_time' => time()
               ];
               $res = $userService->userAppear($map);
               if ($res) {
                   $jsonData = ResponseHelper::buildJsonData(200, '成功');
               } else {
                   $jsonData = ResponseHelper::buildJsonData(400, '申请失败,请及时联系商家');
               }
           } else {
               //用户不存在
               $jsonData = ResponseHelper::buildJsonData(401, '用户信息有误');
           }
        }
        return $this->asJson($jsonData);
    }
}
